package com.qianfeng.front.controller;

import com.qianfeng.front.biz.IOrderBiz;
import com.qianfeng.front.task.OrderTask;
import com.qianfeng.ls.anno.AuthCheckAnno;
import com.qianfeng.ls.entity.GoodsEntity;
import com.qianfeng.ls.entity.OrderEntity;
import com.qianfeng.ls.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Timer;

//结算之前一定需要登录才行
//基于拦截器来实现这么一个动作;添加了自定义注解的才进行拦截,进行登录校验
//1: 订单: 订单id(uuid),创建时间(数据库默认创建时间),customerId(用户id,谁的订单)
//         订单总价(当前的订单商品明细算出来),订单状态(默认未支付), 订单收货地址(地址的id,地址表);

//2: 保存订单信息成功了;

//3: 保存订单详情; 订单详情id(),订单id(这个详情,是谁的详情),商品id(购买的是哪个商品),商品数量(买了几个);
//                 成交价格(单价);

//4: 订单和详情一个事务;
@Controller
public class OrderController {

    @Autowired
    IOrderBiz orderBiz;

    @RequestMapping("jiesuan")
    @AuthCheckAnno  //用户必须登录以后,才能够进行结算
    public String jiesuan(String[] goodscheck, String type, HttpServletRequest request) {

        if ("now".equals(type)) { //结算购物车里面所有的商品
            Map<String, GoodsEntity> shopCar = (Map<String, GoodsEntity>) request.getSession().getAttribute("shopCar");
            goodscheck = shopCar.keySet().toArray(new String[shopCar.keySet().size()]);
        }

        //1:得到所有的商品id进行结算
        //2: 得到当前是哪个用户在购买
        UserEntity customer = (UserEntity) request.getSession().getAttribute("customer");
        int aid = customer.getAid();

        //创建订单信息
        OrderEntity order = orderBiz.createOrder(goodscheck, aid);

        //订单创建成功以后,需要一个定时器来确定30分钟还没有支付,就要失效;

        //1:怎么设置一个定时器?
        Timer timer = new Timer(); //Controller . 单例
        timer.schedule(new OrderTask(orderBiz, order.getOid(), timer), 30 * 1000);//为了测试设置10秒钟

        //2: 我支付了以后,取消定时器!!!

        //把这个timer保存到applicationContext的作用域里面
        request.getServletContext().setAttribute(order.getOid(), timer);

        request.setAttribute("order", order);

        return "orderinfo";
    }

    //支付方法
    @RequestMapping("topaly")
    public String topaly(String oid, HttpServletRequest request) {

        //只要他支付成功,我们就必须要取消定时器;
        Timer timer = (Timer) request.getServletContext().getAttribute(oid);
        timer.cancel();
        request.getServletContext().removeAttribute(oid);

        return "success";
    }

}
